package com.cus.tom.transfer.trans.service;

import static com.cus.tom.transfer.trans.io.DirectoryReader.LOG_TAG;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.BuildConfig;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.utils.ToastUtil;
import com.plata.base.utils.WeakHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class AppService extends Service {

    int index = 0;
    ArrayList<MediaData> list;
    Set<String> set = new HashSet<>();
    WeakHandler h = new WeakHandler();
    private static PowerManager.WakeLock wakeLock = null;

    void acquireLocks() {
        releaseLocks();
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG + ":AppService");
            wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
            Log.d(LOG_TAG, "WakeLock acquired for 10 minutes");
        }
    }

    void releaseLocks() {
        if (wakeLock != null) {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                Log.d(LOG_TAG, "WakeLock released");
            }
            wakeLock = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseLocks();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }
        acquireLocks();
        int from = intent.getIntExtra("from", 0);
        if (from == 0) {
            set.clear();
            index = 0;
            list = intent.getParcelableArrayListExtra("list");
            if (list == null || list.isEmpty()) {
                stopSelf();
                return START_NOT_STICKY;
            }
            install(list.get(0).getPath());
            return START_STICKY;
        } else if (from == 1) {
            if (list == null || list.isEmpty()) {
                stopSelf();
                return START_NOT_STICKY;
            }
            String s = intent.getStringExtra("pkg");
            int j = -1;
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).pkg.equals(s)) {
                    index = i;
                    String name = intent.getStringExtra("name");
                    ToastUtil.showShortToast(App.getApp(), name + "已安装");
                    break;
                }
            }
            if (j >= list.size()) {
                finish();
                return START_NOT_STICKY;
            }
        } else if (from == 2) {
            if (list == null || list.isEmpty()) {
                stopSelf();
                return START_NOT_STICKY;
            }
            if (++index >= list.size()) {
                finish();
                return START_NOT_STICKY;
            } else {
                install(list.get(index).getPath());
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void finish() {
        Intent i = new Intent(Const.INSTALL_FINISH);
        i.setPackage(BuildConfig.APPLICATION_ID);
        sendBroadcast(i);
        h.postDelayed(() -> {
            stopSelf();
        }, 500);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void install(String newApkPath) {
        if (set.contains(newApkPath)) {
            return;
        }
        set.add(newApkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(newApkPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(App.getApp(), BuildConfig.APPLICATION_ID, apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
